package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.lanjiu.lib.imclient.dto.user.UserDto;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.utils.crypto.DES;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.ChooseAccountAdapter;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.LoginView;
import com.ljkj.cordial.chat.util.ButtonSubmitStateUtil;
import com.ljkj.cordial.chat.util.InitializeKit;
import com.ljkj.cordial.chat.widget.RectButtonHintDialog;
import com.nic.view.util.JToast;
import com.nic.view.util.Utility;
import com.nic.view.widget.CircleImageView;
import com.nic.view.widget.ContainsEmojiEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 登录
 */
public class LoginActivity extends AppEventActivity<LoginView> implements LoginView.LoginCallback {


    @BindView(R.id.tv_forget)
    TextView tvForget;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_account)
    AppCompatAutoCompleteTextView tvAccount;
    @BindView(R.id.cb_is_visitor)
    CheckBox cbIsVisitor;
    @BindView(R.id.cb_isOpen)
    CheckBox cbIsOpen;
    @BindView(R.id.tv_password)
    ContainsEmojiEditText tvPassword;
    @BindView(R.id.iv_avatar)
    CircleImageView ivAvatar;

    private int type;
    private UserTableBean loginUser;


    @Override
    public int getContentLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        getToolbar().setNavigationIcon(R.mipmap.tab_ic_back_close);
        type = getIntent().getIntExtra(Canstants.KEY_REGISTER_OR_VISITER, Canstants.STATE_REGISTER_LOGIN);
        UserTableBean u = ChatApp.getInstance().get();
        if (Canstants.STATE_VISITER_LOGIN == type) {
            tvForget.setVisibility(View.GONE);
            cbIsVisitor.setChecked(true);
        } else if (Canstants.STATE_REGISTER_LOGINOUT == type) {
            new RectButtonHintDialog(this)
                    .setTitle("下线通知")
                    .setContent("该账号已在另一台设备登录！")
                    .setSubmit("确认", v -> {
                    }).show();
        }
        tvForget.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tvForget.getPaint().setAntiAlias(true);//抗锯齿

        List<UserTableBean> uList = DbController.getInstance().getRead().getUserTableBeanDao().queryBuilder().list();
        if (!uList.isEmpty()) {
            List<UserTableBean> createList = new ArrayList<>();
            for (UserTableBean userTableBean : uList) {
                if (UserTableBean.TYPE_CREATOR == userTableBean.getCreateState()
                        && UserTableBean.TYPE_REGISTER.equals(userTableBean.getUserType())) {

                    createList.add(userTableBean);
                    if (u != null && !TextUtils.isEmpty(u.getUserId()) && u.getUserId().equals(userTableBean.getUserId())) {
                        loginUser = userTableBean;
                        tvAccount.setText(loginUser.getUserId());
                        tvPassword.setText(DES.decode(loginUser.getSecret()));
                    }
                }
            }
            ChooseAccountAdapter accountAdapter = new ChooseAccountAdapter(this, createList);
            tvAccount.setAdapter(accountAdapter);
            tvAccount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (isFinishing()) {
                        return;
                    }
                    try {
                        //获取焦点显示下拉
                        AppCompatAutoCompleteTextView autoCompleteTextView = (AppCompatAutoCompleteTextView) v;
                        if (hasFocus) {
                            autoCompleteTextView.showDropDown();
                            Utility.getUtility().closeKeyboard(v.getContext());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            tvAccount.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    loginUser = createList.get(position);
                    tvPassword.setText(DES.decode(loginUser.getSecret()));
                }
            });
        }
        cbIsOpen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    tvPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    tvPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        new ButtonSubmitStateUtil(tvRegister, tvAccount, tvPassword) {
            @Override
            public boolean checkState() {
                return check();
            }
        };
    }

    private boolean check() {
        return !TextUtils.isEmpty(tvAccount.getText())
                && !TextUtils.isEmpty(tvPassword.getText()) && tvPassword.getText().length() >= 6;
    }

    public static void jumpTo(Activity context, int type) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(Canstants.KEY_REGISTER_OR_VISITER, type);
        context.startActivityForResult(intent, Canstants.REQUEST_CODE_BACK);
    }

    @OnClick({R.id.tv_forget, R.id.tv_login, R.id.tv_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_forget:
                ForgetPasswordActivity.jumpTo(this, Canstants.STATE_REGISTER);
                break;
            case R.id.tv_login:
                if (check() && null != obtainView()) {
                    String password = DES.encode(tvPassword.getText().toString());
                    obtainView().doRegisteredLogin(tvAccount.getText().toString(), password);
                }
                break;
            case R.id.tv_register:
                if (loginUser != null) {//临时入口
//                    loginUser.setSecret(tvPassword.getText().toString());
//                    ChatApp.getInstance().put(loginUser);
//                    openActivity(ChatMainActivity.class);
//                    finish();
//                    return;
                }
                if (check() && null != obtainView()) {
                    String password = DES.encode(tvPassword.getText().toString());
                    obtainView().doRegisteredLogin(tvAccount.getText().toString(), password);
                }
                break;
        }
    }


    @Override
    protected LoginView bindNettyMessageView() {
        return new LoginView(this);
    }

    @Override
    public void onLoginCallback(int code, String msg, UserDto data) {
        if (IMSContacts.ResponseCode.SUCCESS == code && data != null) {
            if (!TextUtils.isEmpty(data.getUserId())) {
//                SharedUtils.put(this, Canstants.KEY_UserId, data.getUserId());
//                SharedUtils.put(this, Canstants.KEY_UseType, UserTableBean.TYPE_REGISTER);
//                SharedUtils.put(this, Canstants.KEY_Nickname, data.getNickname());
//                SharedUtils.put(this, Canstants.KEY_Avatar, data.getAvatar());

                UserTableBean user = new UserTableBean();
                String password = DES.encode(tvPassword.getText().toString());
                user.setSecret(password);
                user.insert(data);

                String obviousPassword = tvPassword.getText().toString();
                if ("123456".equals(obviousPassword)) {
                    new RectButtonHintDialog(this)
                            .setTitle("账号安全")
                            .setContent("您的密码过于简单，建议您修改密码")
                            .setLeftSubmit("立即登录", v -> jumpToChaiMain())
                            .setRightSubmit("修改密码", v -> ForgetPasswordActivity.jumpToForResult(this, Canstants.STATE_FIND_PASSWORD))
                            .show();
                } else {
                    jumpToChaiMain();
                }
            }

        } else {
            if (TextUtils.isEmpty(msg)) msg = "登录失败";
            JToast.showShort(this, msg);
        }
    }

    public void jumpToChaiMain() {
        InitializeKit.clear();
        openActivity(ChatMainActivity.class);
        setResult(Canstants.REQUEST_CODE_BACK);
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Canstants.REQUEST_CODE_BACK && resultCode == Canstants.REQUEST_CODE_BACK) {
            setResult(Canstants.REQUEST_CODE_BACK);
            finish();
        } else if (requestCode == 100 && resultCode == 100) {
            tvPassword.setText(null);
        }
    }
}
